package com.zjp.responsibility;

import java.util.Objects;

public abstract class Support {

    private String name;
    private Support next;

    public Support(String name) {
        this.name = name;
    }

    public Support setNext(Support next) {
        this.next = next;
        return next;
    }

    public final void support(Trouble trouble) {
        if (resolve(trouble)) {
            done(trouble);
        } else if (Objects.nonNull(next)) {
            next.support(trouble);
        } else {
            fail(trouble);
        }
    }

    @Override
    public String toString() {
        return "[" + name + ']';
    }

    /**
     * 解决问题
     *
     * @param trouble 问题
     * @return 解决状态
     */
    protected abstract boolean resolve(Trouble trouble);

    // 解决
    protected void done(Trouble trouble) {
        System.out.println(trouble + " is resolved by " + this + " .");
    }

    // 未解决
    protected void fail(Trouble trouble) {
        System.out.println(trouble + " cannot be resolved .");

    }


}
